package com.zl.learning.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class TestExpose {

    private User user;

    @Before
    public void beforeTest(){
        user = new User("lemon",27);
        List<String> list = new ArrayList<String>();
        list.add("l1");
        list.add("l2");
        user.setList(list);
    }

    @Test
    public void test1(){
        //使用 new Gson();
        Gson g1 = new Gson();
        String str = g1.toJson(user);
        System.out.println(str); //{"username":"lemon","age":27,"list":["l1","l2"]}
    }

    @Test
    public void test2(){
        //使用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        Gson g2 = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        String str = g2.toJson(user);
        System.out.println(str); //{"username":"lemon"}

        String str2 = "{\"username\":\"lemon\",\"age\":27,\"list\":[\"l1\",\"l2\"]}";
        User u = g2.fromJson(str2,User.class);
        System.out.println(u);
    }

    public static class User {
        @Expose
        private String username;
        @Expose(deserialize = true,serialize = false)
        private Integer age ;
        @Expose(serialize = true)
        private List<String> list;

        public User(String username, Integer age) {
            super();
            this.username = username;
            this.age = age;
        }

        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public List<String> getList() {
            return list;
        }
        public void setList(List<String> list) {
            this.list = list;
        }

        @Override
        public String toString() {
            return "User{" +
                    "username='" + username + '\'' +
                    ", age=" + age +
                    ", list=" + list +
                    '}';
        }
    }
}
